﻿using System;
using System.Data.SqlClient;

namespace SimpleAsynch
{
    public class Program
    {
        public static String ConnectionString;
        public static int Count;

        public static SqlCommand Command;
        public static IAsyncResult Result;
        public static SqlDataReader Reader;
        public static SqlConnection Connection;

        public static void Main()
        {
        }

        public delegate void ResponseDelegate(IAsyncResult result);

        public static event ResponseDelegate QueryOneResponse;
        public static event ResponseDelegate QueryTwoResponse;

        public static void Initialize()
        {
            QueryOneResponse += new ResponseDelegate(OnQueryOneResponse);
            QueryTwoResponse += new ResponseDelegate(OnQueryTwoResponse);
        }

        public static void Connect()
        {
            ConnectionString =
                @"data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=NORTHWND.MDF;User Instance=true";
            //ConnectionString = "Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;Asynchronous Processing=true";
            Connection = new System.Data.SqlClient.SqlConnection(ConnectionString);
            Connection.Open();
        }

        public static void RunQueryOne()
        {
            Command = new SqlCommand("WAITFOR DELAY '00:00:03'; SELECT [OrderID], [EmployeeID], [OrderDate], [CustomerID], [RequiredDate], [ShippedDate], [ShipAddress] FROM [Orders]", Connection);
            Result = Command.BeginExecuteReader((result)=>
                                                    {
                                                        if(QueryOneResponse!=null)
                                                        {
                                                            QueryOneResponse(result);
                                                        }
                                                    }, null);
        }

        public static void RunQueryTwo()
        {
            Command = new SqlCommand("SELECT * FROM [Orders]", Connection);
            Result = Command.BeginExecuteReader((result) =>
            {
                if (QueryTwoResponse != null)
                {
                    QueryTwoResponse(result);
                }
            }, null);
        }

        public static void OnQueryOneResponse(IAsyncResult result)
        {
            Reader = Command.EndExecuteReader(result);
        }

        public static void OnQueryTwoResponse(IAsyncResult result)
        {
            Reader = Command.EndExecuteReader(result);
        }
    }
}
